package org.yang.snake.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.yang.snake.dao.SysMenuDao;
import org.yang.snake.model.SysMenu;
import org.yang.snake.model.SysUser;
import org.yang.snake.dao.SysUserDao;
import org.yang.snake.security.SnakeUser;
import org.yang.snake.service.SysUserService;
import org.yang.snake.util.Result;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;

import javax.annotation.Resource;
import java.util.List;

/**
 * 用户(SysUser)表服务实现类
 *
 * @author shichenyang
 * @since 2019-08-21 11:05:17
 */
@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
    @Resource
    private SysUserDao sysUserDao;

    @Resource
    private SysMenuDao sysMenuDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public SysUser getById(Long id) {
        return this.sysUserDao.getById(id);
    }

    /**
     * 查询多条数据
     *
     * @param page 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public Result listAll(SysUser sysUser,Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<SysUser> list = sysUserDao.listAll(sysUser);
        PageInfo info = new PageInfo(list);
        return Result.ok("查询成功", info.getList(), info.getTotal());
    }

    /**
     * 新增数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public Result insert(SysUser sysUser) {
        return sysUserDao.insert(sysUser)>0?Result.ok("添加成功") : Result.err("添加失败");
    }

    /**
     * 修改数据
     *
     * @param sysUser 实例对象
     * @return 实例对象
     */
    @Override
    public Result update(SysUser sysUser) {
        return sysUserDao.update(sysUser)>0?Result.ok("修改成功") : Result.err("修改失败");
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public Result deleteById(Long id) {
        return this.sysUserDao.deleteById(id) > 0?Result.ok("删除成功") : Result.err("删除失败");
    }

    @Override
    public UserDetails loadByUsername(String username) {
        SysUser user = sysUserDao.loadByUsername(username);
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<SysMenu> list = sysMenuDao.listByUserRole(username);
        list.forEach(item -> {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(item.getCode());
            authorities.add(authority);
        });
        authorities.add(new SimpleGrantedAuthority(user.getRoleCode()));
        SnakeUser snakeUser = new SnakeUser(user.getUsername(), user.getPassword(), authorities, user.getId(), user.getDeptId());
        return snakeUser;
    }
}